package com.iussoft.receiveData.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.api.api.ApiService;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.exception.BusinessException;
import com.apache.exception.ServiceException;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.StrUtil;
import com.iussoft.receiveData.manager.ReceiveManager;
import com.iussoft.tools.LoggerUtil;
import com.iussoft.tools.RequestMessage;
import com.iussoft.tools.SpringContextLoader;
import com.iussoft.tools.UnityErrorCode;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description: 统一对外数据接收接口（http、socket,restful)
 * @author: Hou Dayu
 * @date: Created in 2020/3/2
 */
@Service("receiveService")
public class ReceiveServiceImpl implements ApiService {

    @Autowired
    private ReceiveManager receiveManager;

    @Override
    public ResultEntity doService(ParamsVo paramsVo) throws ServiceException {
        ResultEntity result = new ResultEntity();
        result.setResult("false");
        String requestKey = StrUtil.doNull(paramsVo.getMethodKey(),paramsVo.getParamsToStr("requestCode"));
        if (StrUtil.isNull(requestKey)) {
            result.setMessage("请指定需要执行的接口");
            return result;
        }
        try {
            String exchangeMode ="",exchangeType = "1";
            JSONObject map = checkPermissions(paramsVo,requestKey);
            if(null != map){
                paramsVo.setParams("dxpInterfaceInfo", map.toJSONString());
                exchangeMode = map.getString("exchangeMode");
                exchangeType = StrUtil.doNull(map.getString("exchangeType"),"1");
            }
            if(null == paramsVo.getObj()){
                RequestMessage msg = new RequestMessage();
                msg.setSourceMsg(JSON.toJSONString(paramsVo.getParams()));
                msg.setContent(JSON.parseObject(msg.getSourceMsg()));
                paramsVo.setObj(msg);
            }
            PluginConnector plugin = null;
            if("11".equalsIgnoreCase(exchangeMode)){//被动推送接收数据
                plugin = (PluginConnector) SpringContextLoader.getBean("receive-sendmsg");
            } else if("12".equalsIgnoreCase(exchangeMode)) {//主动抓取接收数据
                plugin = (PluginConnector) SpringContextLoader.getBean("synchronize-data");
            }else if("2".equalsIgnoreCase(exchangeMode) && "1".equals(exchangeType)){//动过发送数据
                plugin = (PluginConnector) SpringContextLoader.getBean("retrieve-data");
            } else if("2".equalsIgnoreCase(exchangeMode) && "2".equals(exchangeType)){//异步获取数据
                plugin = (PluginConnector) SpringContextLoader.getBean("receive-sendmsg");
            } else {//直接调IUS接口
                Object obj = SpringContextLoader.getBean(requestKey);
                if(null == obj) {
                    RequestMessage reqMsg = (RequestMessage) paramsVo.getObj();
                    result = LoadRpcService.service().doService("iusService", "dymicSql", "xml", reqMsg.getContent(), null);
                    return result;
                } else {
                    plugin = (PluginConnector)obj;
                }
            }
            //根据DealType参数实例化的bean调用对应的插件方法
            result = (ResultEntity)plugin.execute(paramsVo);
        } catch(NoSuchBeanDefinitionException e1){
            LoggerUtil.infoSource("Receive service execution: Interface code for {},execption describe for {},execption info for {}",requestKey,"待执行的接口不存在，请确认输入是否正确",e1.getMessage());
            throw new ServiceException(UnityErrorCode.NOT_BEAN.getValue(), "待执行的接口["+requestKey+"]不存在，请确认输入是否正确");
        } catch (Exception e){
            e.getStackTrace();
            LoggerUtil.infoSource("Receive service execution: Interface code for {},execption describe for {},execption info for {}",requestKey,"接口执行异常",e.getMessage());
            if(e instanceof BusinessException){
                throw new ServiceException(e.getMessage());
            }
            throw new ServiceException(UnityErrorCode.UNKNOWN_ABNORMAL.getValue(),"执行接口[" + requestKey + "]异常");
        }
        return result;
    }

    private JSONObject checkPermissions(ParamsVo paramsVo, String requestKey) throws ServiceException {
        if(null != paramsVo.getObj()){
            RequestMessage reqMsg = (RequestMessage)paramsVo.getObj();
            return reqMsg.getContent();
        }
        return receiveManager.getDxSysIntRelation(requestKey);
    }
}
